package com.example.controller;


import com.example.config.AppFinal;
import com.example.mapper.ArticleInfoMapper;
import com.example.model.ArticleInfo;
import com.example.model.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/article")
public class ArticleInfoController {

    @Resource
    private ArticleInfoMapper articleInfoMapper; //注入ArticleInfoMapper对象

    //根据文章的id删除文章
    @RequestMapping("/del")
    public int delById(@RequestParam int id){
        return articleInfoMapper.delById(id);
    }

    //根据文章id修改文章
    @RequestMapping("/update")
    public Object update(@RequestParam String title, @RequestParam String content, @RequestParam int id){
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setTitle(title);
        articleInfo.setContent(content);
        articleInfo.setId(id);
        int ret = articleInfoMapper.updateById(articleInfo);
        return articleInfo;
    }

    //根据id得到文章详情
    @RequestMapping("/getdetail")
    //如果前端不传递id，则后端接口报错
    public ArticleInfo getDetail(@RequestParam int id){
        return articleInfoMapper.getDetail(id);
    }

    //添加文章
    @RequestMapping("/add")
    @ResponseBody
    public Object add(@RequestParam String title, @RequestParam String content, HttpServletRequest request){
        //得到session
        HttpSession session = request.getSession(false);
        Object user1 = null;
        //判断session信息
        if(session == null ||
                (user1 = session.getAttribute(AppFinal.USERINFO_SESSIONKEY)) == null){
            return 0;
        }
        User user = (User)user1; //得到用户信息
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setTitle(title);
        articleInfo.setContent(content);
        articleInfo.setUid(user.getId());
        int ret = articleInfoMapper.add(articleInfo);
        return articleInfo;
    }

}
